<?php


namespace app\admin\system\controller;


use app\admin\system\validate\AdminLoginValidate;
use app\common\controller\BaseAdminController;
use app\common\service\PasswordService;
use app\model\SysAdmin;
use common\service\JwtService;
use support\exception\BadException;
use yzh52521\JwtAuth\facade\JwtAuth;

class LoginController extends BaseAdminController
{
    protected $noNeedLogin = [
        'login',
        'test',
    ];

    public function login()
    {
        AdminLoginValidate::goCheck(input());

        $username = input('username');
        $password = input('password');
        $user = SysAdmin::where([
            'username' => $username
        ])->field(['id', 'password', 'salt', 'status'])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }
        if (!PasswordService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }

//        $token = md5($username . $password . RandomUtil::randomStr());
//        $user->token = $token;
        $user->ip = request()->getRealIp();
        $user->save();
        $config = JwtAuth::getConfig('admin');
        $token = JwtService::generateToken($user['id'], 'admin');
        return $this->success([
            "tokenName" => "Authorization",
            'tokenValue' => $token,
            'token_type' => $config->getType(),
            'expires_in' => $config->getExpires(),
            'refresh_in' => $config->getRefreshTTL(),
        ]);
    }

    public function loginOut()
    {
        JwtService::logout('admin');
        return $this->success();
    }

}